package cn.edu.sasu;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import cn.edu.sasu.domain.Users;
import cn.edu.sasu.utils.StringUtil;
import cn.edu.sasu.webservice.LoginService;
import cn.edu.sasu.webservice.impl.LoginServiceImpl;

/**
 * 登录的Activity
 * 
 * @author yubaolinfish
 * 
 */
@SuppressLint("HandlerLeak")
public class LoginActivity extends Activity {
	private EditText et_number = null, et_password = null;
	private Intent intent = null;
	private LoginService loginService = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		loginService = new LoginServiceImpl();

		et_number = (EditText) findViewById(R.id.et_number);
		et_password = (EditText) findViewById(R.id.et_password);
	}

	// 登录
	public void login(View view) {
		String number = et_number.getText().toString();
		String password = et_password.getText().toString();
		if (StringUtil.isBlank(number)) {
			Toast.makeText(LoginActivity.this, R.string.enter_account,
					Toast.LENGTH_SHORT).show();
			return;
		}
		if (StringUtil.isBlank(password)) {
			Toast.makeText(LoginActivity.this, R.string.enter_account,
					Toast.LENGTH_SHORT).show();
			return;
		}

		final Map<String, String> parmes = new HashMap<String, String>();

		if (!number.contains("@")) {
			parmes.put("user.userName", number);
		} else {
			parmes.put("user.userNumber", number + "@163.com");
		}

		parmes.put("user.userPassword", password);

		new Thread() {

			public void run() {
				data = loginService.login(parmes);

				Log.i("Test", "data  " + data);

				handler.sendEmptyMessage(1);
			};
		}.start();

	}

	private String data = "";
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				// 登录成功
				Users.setUser(loginService.parseUser(data));
				if (Users.getUser() == null) {
					Toast.makeText(LoginActivity.this, R.string.password_error,
							Toast.LENGTH_SHORT).show();
					return;
				}
				setResult(RESULT_OK);
				finish();
				break;

			}
		};
	};

	// 跳转到注册页面
	public void register(View view) {
		intent = new Intent(this, RegisterActivity.class);
		this.startActivityForResult(intent, 1);
	}

	// 跳转到主页面
	public void returnIndex(View view) {
		this.setResult(RESULT_OK);
		finish();
	}

}